//
//  ImageDownloader.m
//  tableViewLazyDemo
//
//  Created by kingboyrang on 2021/11/20.
//  Copyright © 2021 wulanzhou. All rights reserved.
//

#import "ImageDownloader.h"
#import "FileUtils.h"

@interface ImageDownloader (){
    
    NSURLSessionDataTask *_dataTask;
}

@end


@implementation ImageDownloader

- (instancetype)initWithUrlStr:(NSString *)urlStr{
    if (self = [super init]) {
        self.urlStr = urlStr;
    }
    return self;
}

//下载
- (void)start{
    
    NSAssert(self.urlStr != nil, @"图片下载地址不能为空！");
    //NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]];
    
    
    //保存在NSCache中()
    
    
    //获取本地
    UIImage *cacheImage = [FileUtils getCacheImageForKey:self.urlStr];
    if(cacheImage){
        NSLog(@"获取缓存图片");
        if (self.completionHandler) {
            self.completionHandler(cacheImage);
        }
        return;
    }
    
    //网络加载
    __weak typeof(self) wself = self;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    _dataTask = [session  dataTaskWithURL:[NSURL URLWithString:self.urlStr] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        UIImage *img = nil;
        if (error) {
            NSLog(@"加载失败");
        }else{
            img = [UIImage imageWithData:data];
            //缓存到本地
            [FileUtils cacheImage:data key:wself.urlStr];
        }
        if (wself.completionHandler) {
            wself.completionHandler(img);
        }
    }];
    [_dataTask resume];
}

//取消
- (void)cancel{
    if (_dataTask) {
        [_dataTask cancel];
        _dataTask = nil;
    }
}

@end
